<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <c-select
          clearable
          placeholder="产品类型"
          v-model="params['is_rural_dev.eq']"
          @change="getAllData()"
          :options="enumIsralDev"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          clearable
          v-model="params['channel_type.eq']"
          @change="getAllData()"
          placeholder="业务模式"
          :options="enumChannelType"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="客户名称"
          clearable
          @change="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumReviewApprovalSelect"
          clearable
          @change="searchParams"
          placeholder="项目状态"
          v-model="selectStatus"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.iou_no"
          placeholder="借据号"
          clearable
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.lender_idcard"
          placeholder="身份证号"
          clearable
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.register_no"
          placeholder="营业执照/统一信用代码"
          clearable
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.batch_no"
          placeholder="提交批次号"
          clearable
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <select-child-bank
          clearable
          v-model="params['bank_id.eq']"
          @change="getAllData()"
          placeholder="导入银行(可输入过滤)"
        ></select-child-bank>
      </el-form-item>
      <el-form-item>
        <select-system-enum
          placeholder="银行类型"
          filterable
          type="bankClass"
          clearable
          @change="getAllData()"
          v-model="params['bank_type.eq']"
        ></select-system-enum>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="资料状态"
          :options="{
            0: '未完善',
            1: '已完善',
          }"
          v-model="params['datum_status.eq']"
          clearable
          @change="getAllData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="贷后状态"
          :options="{
            1: '在保',
            5: '解保',
          }"
          v-model="params['load_beh_status.eq']"
          clearable
          @change="getAllData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="form-control-ml"
          v-model="params['load_end_date.lt']"
          placeholder="放款到期"
          value-format="yyyy-MM-dd"
          @change="getAllData()"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getAllData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('限率业务')"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>
    <div class="card my-2">
      <div class="card-body" v-loading="countLoading">
        <span class="h5 text-muted">
          项目共计：
          <span class="text-danger">{{ tableCount }}</span>
        </span>
        <span class="h5 text-muted ml-5">
          金额合计：
          <span class="text-danger">{{ tableFunds || '-' }}</span>
          万元
        </span>
      </div>
    </div>
    <c-table
      border
      v-loading="loading"
      ref="table"
      class="table-sm"
      :columns="tableColumns"
      :data="tableData"
    >
      <template v-slot:status="scope">
        <div :class="`text-${scope.row.statusStyle}`">
          <div :title="scope.row.ex_des">
            <span v-if="+scope.row.import_status > 1 && scope.row.ex_des">
              {{ scope.row.statusLabel + `: ${scope.row.ex_des}` }}
            </span>
            <span v-else>{{ scope.row.statusLabel }}</span>
          </div>
          <small :class="`text-${scope.row.replaceStatusStyle}`">
            {{ scope.row.replaceStatus }}
          </small>
          <div
            v-if="scope.row.back_reason && ![2, 4, 5, 6, 7].includes(+scope.row.review_approval)"
            :class="+scope.row.import_status === 2 ? 'text-warning' : 'text-danger'"
          >
            <span v-if="+scope.row.import_status === 3">
              拒绝:
              <span v-html="xss(scope.row.back_reason)"></span>
            </span>
            <span v-else>
              退回:
              <span v-html="xss(scope.row.back_reason)"></span>
            </span>
          </div>
        </div>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        :page-sizes="[15, 100, 200, 500, 1000]"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <project-new-dialog
      :visible.sync="editVisible"
      :table-id="tableId"
      :form-data="editData"
      @success="getData()"
    ></project-new-dialog>

    <list-dialog :visible.sync="signVisible" :related-id="customerId"></list-dialog>
  </div>
</template>

<script>
import {
  enumReviewApproval,
  enumReviewStyle,
  enumReplaceStatus,
  enumReplaceStatusStyle,
  enumReviewApprovalSelect,
} from '@/bank/views/limit/index'
import SelectChildBank from '@/bank/components/select/SelectChildBank'
import { exportTable } from '@/bank/plugins/export'
import SelectSystemEnum from '@/cadmin/components/select/SelectSystemEnum'
import xss from 'xss'
import ProjectNewDialog from '@/cadmin/views/project/components/ProjectNewDialog.vue'
import ListDialog from '@/cadmin/views/org/components/sign/ListDialog'
export default {
  components: {
    SelectChildBank,
    SelectSystemEnum,
    ProjectNewDialog,
    ListDialog,
  },
  props: {},
  data() {
    return {
      xss,
      enumReviewApprovalSelect,
      enumIsralDev: {
        1: '乡村振兴贷',
        0: '黔农十二贷',
      },
      enumChannelType: {
        0: '存量业务',
        1: '增量业务',
      },
      tableName: 'datum_one_county_industry',
      params: {
        index: 1,
        size: 10,
        customer_name: '',
        'import_status.eq': '',
        subKey: 'project_apply_batch.project_apply_batch_id',
      },
      order: { N1is_history: 'asc', N2create_time: 'desc' },
      tableColumns: [
        {
          attrs: { label: '借款客户', prop: 'customer_name', minWidth: '120px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '联系电话', prop: 'corp_phone', align: 'center' } },
        { attrs: { label: '贷款金额(万元)', prop: 'warranty_amount', align: 'center' } },
        { attrs: { label: '证件号', prop: 'customerNo', align: 'center' } },
        { attrs: { label: '银行项目经理', prop: 'bank_user_name', align: 'center' } },
        { attrs: { label: '创建时间', prop: 'create_time', align: 'center', width: 90 } },
        {
          attrs: { label: '导入银行', prop: 'bank_name', align: 'left', width: '110px' },
        },
        {
          attrs: { label: '提交银行', prop: 'submitOrg', align: 'left', width: '110px' },
        },
        {
          attrs: { label: '提交时间', prop: 'submitTime', align: 'left', width: '90px' },
        },
        {
          attrs: { label: '业务类型', prop: 'projectType', align: 'center' },
        },
        { attrs: { label: '提交批次号', prop: 'batch_no', align: 'center' } },
        {
          attrs: { label: '项目状态', prop: 'statusLabel', align: 'center', width: '110px' },
          slot: 'status',
        },
        {
          attrs: { label: '操作', align: 'center', width: '160px', fixed: 'right' },
          operations: [
            {
              content: '修改',
              icon: 'fa fa-edit',
              event: this.handleEdit,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger py-0 px-2' },
              event: this.handleDelete,
              ifRender: row => [0, 3, 9].includes(+row.review_approval) || +row.import_status > 1,
            },
            { content: '签约', icon: 'fa fa-chain-broken', event: this.handlerSign },
          ],
        },
      ],
      tableData: [],
      tableCount: 0,
      selectStatus: '',
      loading: false,
      countLoading: false,
      exportLoading: false,
      tableFunds: 0,

      editData: {},
      tableId: '',
      editVisible: false,

      signVisible: false,
      customerId: '',
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getAllData()
  },
  mounted() {},
  methods: {
    handlerSign(row = {}) {
      this.signVisible = true
      this.customerId = row.customer_related_id || ''
    },
    handleEdit(row) {
      this.editVisible = true
      this.tableId = row.customer_related_id
      this.editData = { ...row }
    },
    searchParams(v) {
      this.params['back_reason.neq'] = ''
      this.params['review_approval.in'] = ''
      this.params['import_status.in'] = ''
      if (+v === 100) {
        this.params['import_status.in'] = '2,3'
      } else if (+v === 9) {
        this.params['import_status.in'] = '2,3'
        this.params['back_reason.neq'] = `''`
      } else {
        this.params['review_approval.in'] = v
      }
      this.getAllData()
    },
    handleSizeChange(val) {
      this.params.size = val
      this.getAllData()
    },
    getAllData() {
      this.getData()
      this.getCountFunds()
    },
    getCountFunds() {
      const { index, size, ...params } = this.params
      params.groupFunc = 'round(sum(warranty_amount)|2)'
      this.countLoading = true
      this.$api
        .getData(this.$serviceName, this.tableName, params)
        .then(res => {
          const data = res?.data?.[0] ?? {}
          this.tableFunds = data.p || 0
        })
        .finally(() => {
          this.countLoading = false
        })
    },
    handleDelete(row = {}) {
      this.$utils
        .msgbox({
          message: `确定删除客户${row.customer_name}?`,
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, this.tableName, row.customer_related_id),
        })
        .then(() => {
          this.getData()
          this.$message.success('删除成功！')
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    dataAdapter(item) {
      item.statusLabel = enumReviewApproval[item.review_approval]
      item.statusStyle = enumReviewStyle[item.review_approval]
      item.replaceStatus = enumReplaceStatus[item.is_replace] || ''
      item.replaceStatusStyle = enumReplaceStatusStyle[item.is_replace]
      const submitData = item?.project_apply_batch?.[0] ?? {}
      item.submitOrg = submitData.submit_client_name || '未申报'
      item.submitTime = submitData.create_time
      if (+item.import_status !== 1) {
        item.statusLabel = '项目异常'
        item.statusStyle = 'danger'
      }
      item.projectType = `${this.enumIsralDev[item.is_rural_dev]}(${
        this.enumChannelType[item.channel_type]
      })`
      item.customerNo = +item.customer_type === 1 ? item.register_no : item.lender_idcard
      item.bank_user_name = item.bank_user_name || item.submit_person_name
      return item
    },
    getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData('credit', this.tableName, this.params, this.order)
        .then(res => {
          const data = res?.data ?? {}
          this.tableData = (data.data ?? []).map(this.dataAdapter)
          this.tableCount = data.totalCount ?? 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    exportExcel(name) {
      this.exportLoading = true
      const { index, size, ...params } = this.params
      exportTable({
        columns: this.tableColumns,
        table: this.tableName,
        params: params,
        order: this.order,
        adapter: this.dataAdapter,
        filename: name,
      }).finally(() => {
        this.exportLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
